﻿using System;
using System.Xml;
using Sherwood.Content.Contracts;

namespace Sherwood.Content.UpdateServices
{
    public abstract class MetaUpdaterBase<TMeta> : IMetaXmlUpdater
        where TMeta : class, IMeta, new()
    {
        public IMetaRepository MetaRepository { get; private set; }

        protected MetaUpdaterBase(IMetaRepository metaRepository)
        {
            MetaRepository = metaRepository;
        }

        public IMeta FromXml(IRecord record, IClient client, string usageKey, UpdateMode updateMode, XmlReader reader)
        {
            var meta = MetaRepository.GetMeta<TMeta>(record.Id, client.Id, usageKey);
            if (meta == null && (updateMode == UpdateMode.Create || updateMode == UpdateMode.CreateOrUpdate))
                meta = CreateMeta(record, client, usageKey);
            if(meta == null)
                return null;

            if (updateMode == UpdateMode.Delete)
                MetaRepository.Delete(meta);

            UpdateMeta(meta, reader);

            return meta;
        }

        protected virtual TMeta CreateMeta(IRecord record, IClient client, string usageKey)
        {
            return MetaRepository.CreateNew<TMeta>(record, client, usageKey);
        }

        protected abstract void UpdateMeta(TMeta meta, XmlReader reader);
    }
}